// LogRecordDetailActivity.java
package no.nordicsemi.android.nrfmesh;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import no.nordicsemi.android.nrfmesh.database.entity.LogRecord;
import no.nordicsemi.android.nrfmesh.database.AppDatabase;
import no.nordicsemi.android.nrfmesh.utils.ImpedanceConverter;

public class LogRecordDetailActivity extends AppCompatActivity {
    public static final String EXTRA_LOG_RECORD_ID = "log_record_id";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_record_detail);

        int recordId = getIntent().getIntExtra(EXTRA_LOG_RECORD_ID, -1);
        if (recordId == -1) {
            finish();
            return;
        }

        // 从数据库获取记录
        new Thread(() -> {
            LogRecord record = AppDatabase.getInstance(LogRecordDetailActivity.this)
                    .logRecordDao()
                    .getLogRecordById(recordId);

            runOnUiThread(() -> {
                if (record == null) {
                    finish();
                    return;
                }
                bindViews(record);
            });
        }).start();
    }

    private void bindViews(LogRecord record) {
        TextView tvStartTime = findViewById(R.id.tv_detail_start_time);
        TextView tvEndTime = findViewById(R.id.tv_detail_end_time);
        TextView tvDuration = findViewById(R.id.tv_detail_duration);
        TextView tvGear = findViewById(R.id.tv_detail_gear);
        TextView tvTotalTime = findViewById(R.id.tv_detail_total_time);
        TextView tvSegments = findViewById(R.id.tv_detail_segments);
        TextView tvSegmentParams = findViewById(R.id.tv_detail_segment_params);
        TextView tvConfigName = findViewById(R.id.tv_detail_config_name);

        // 电压1统计
        TextView tvAvgVoltage1 = findViewById(R.id.tv_detail_avg_voltage1);
        TextView tvMaxVoltage1 = findViewById(R.id.tv_detail_max_voltage1);
        TextView tvMinVoltage1 = findViewById(R.id.tv_detail_min_voltage1);

        // 电压2统计
        TextView tvAvgVoltage2 = findViewById(R.id.tv_detail_avg_voltage2);
        TextView tvMaxVoltage2 = findViewById(R.id.tv_detail_max_voltage2);
        TextView tvMinVoltage2 = findViewById(R.id.tv_detail_min_voltage2);

        // 电流统计
        TextView tvAvgCurrent = findViewById(R.id.tv_detail_avg_current);
        TextView tvMaxCurrent = findViewById(R.id.tv_detail_max_current);
        TextView tvMinCurrent = findViewById(R.id.tv_detail_min_current);

        // 阻抗统计
        TextView tvAvgImpedance = findViewById(R.id.tv_detail_avg_impedance);
        TextView tvMaxImpedance = findViewById(R.id.tv_detail_max_impedance);
        TextView tvMinImpedance = findViewById(R.id.tv_detail_min_impedance);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        tvStartTime.setText(sdf.format(record.startTime));
        tvEndTime.setText(sdf.format(record.endTime));

        long seconds = record.duration / 1000;
        long minutes = seconds / 60;
        long remainingSeconds = seconds % 60;
        tvDuration.setText(String.format("%02d:%02d", minutes, remainingSeconds));

        tvGear.setText(String.valueOf(record.gear));
        tvTotalTime.setText(record.totalTime + " 分钟");
        tvSegments.setText(String.valueOf(record.totalSegments));
        
        // 设置配置名称
        if (record.configName != null && !record.configName.isEmpty()) {
            tvConfigName.setText(record.configName);
        } else {
            tvConfigName.setText("未设置");
        }

// 👉 修改段参数显示逻辑
        try {
            record.initSegmentParamsIfNeeded(); // 确保 segmentParams 已初始化
            Map<Integer, Map<String, Object>> segmentParams = record.getSegmentParamsMap();

            if (segmentParams.isEmpty()) {
                tvSegmentParams.setText("无段参数数据");
            } else {
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= record.totalSegments; i++) {
                    Map<String, Object> params = segmentParams.get(i);
                    if (params != null) {
                        // 每段信息放在一行显示，参数之间留适当空格以实现对齐效果
                        sb.append("第").append(i).append("段:          ");

                        // 段时长（毫秒）
                        Object durationObj = params.get("segmentDuration");
                        if (durationObj != null) {
                            int duration = ((Double) durationObj).intValue();
                            sb.append("段时长:").append(String.format("%-4d", duration)).append("ms          ");
                        }

                        // 脉宽（微秒）
                        Object pulseWidthObj = params.get("pulseWidth");
                        if (pulseWidthObj != null) {
                            int pulseWidth = ((Double) pulseWidthObj).intValue();
                            sb.append("脉宽:").append(String.format("%-4d", pulseWidth)).append("μs          ");
                        }

                        // 波形类型
                        Object waveformTypeObj = params.get("waveformType");
                        if (waveformTypeObj != null) {
                            int waveformType = ((Double) waveformTypeObj).intValue();
                            String waveformName = getWaveformName(waveformType);
                            sb.append("波形类型:").append(waveformName);
                        }

                        // 频率（赫兹）
                        Object frequencyObj = params.get("frequency");
                        if (frequencyObj != null) {
                            int frequency = ((Double) frequencyObj).intValue();
                            sb.append("频率:").append(String.format("%-3d", frequency)).append("Hz          ");
                        }


                        sb.append("\n");
                    }
                }
                tvSegmentParams.setText(sb.toString().trim());
            }
        } catch (Exception e) {
            tvSegmentParams.setText("无法解析段参数: " + e.getMessage());
            Log.e("LogRecordDetail", "解析段参数失败", e);
        }

        // 电压1统计
        tvAvgVoltage1.setText(String.format("平均: %.2f V", record.avgVoltage1));
        tvMaxVoltage1.setText(String.format("最大: %.2f V", record.maxVoltage1));
        tvMinVoltage1.setText(String.format("最小: %.2f V", record.minVoltage1));

        // 电压2统计
        tvAvgVoltage2.setText(String.format("平均: %.2f V", record.avgVoltage2));
        tvMaxVoltage2.setText(String.format("最大: %.2f V", record.maxVoltage2));
        tvMinVoltage2.setText(String.format("最小: %.2f V", record.minVoltage2));

        // 电流统计
        tvAvgCurrent.setText(String.format("平均: %.2f A", record.avgCurrent));
        tvMaxCurrent.setText(String.format("最大: %.2f A", record.maxCurrent));
        tvMinCurrent.setText(String.format("最小: %.2f A", record.minCurrent));

        // 阻抗统计 - 数据库中存储的就是Ω值，直接显示
        tvAvgImpedance.setText(String.format("平均: %.2f Ω", record.avgImpedance));
        tvMaxImpedance.setText(String.format("最大: %.2f Ω", record.maxImpedance));
        tvMinImpedance.setText(String.format("最小: %.2f Ω", record.minImpedance));
    }

    // 添加获取波形名称的辅助方法
    private String getWaveformName(int waveformType) {
        switch (waveformType) {
            case 0: return "正向正弦波          ";
            case 1: return "负向正弦波          ";
            case 2: return "双向正弦波          ";
            case 3: return "正向三角波          ";
            case 4: return "负向三角波          ";
            case 5: return "双向三角波          ";
            case 6: return "正向矩形波          ";
            case 7: return "负向矩形波          ";
            case 8: return "双向矩形波          ";
            default: return "未知波形          ";
        }
    }
}
